package com.ruyuan2020.im.xx;



import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.Map;
import java.util.concurrent.*;

public class TaskManager {
    // 任务名称对应的线程池
    private static Map<String, ExecutorService> taskExecutors = new ConcurrentHashMap<>();

    // 初始化线程池
    private static ExecutorService initializeExecutor(String executorName, int poolSize) {
        return new ThreadPoolExecutor(
                poolSize, poolSize,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(),
                new ThreadFactoryBuilder().setNameFormat("Pool-" + executorName).setDaemon(false).build(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    // 获取或初始化线程池
    public static ExecutorService getOrInitializeExecutor(String executorName, int poolSize) {
        ExecutorService executorService = taskExecutors.get(executorName);
        if (null == executorService) {
            synchronized (TaskManager.class) {
                executorService = taskExecutors.get(executorName);
                if (null == executorService) {
                    executorService = initializeExecutor(executorName, poolSize);
                    taskExecutors.put(executorName, executorService);
                }
            }
        }
        return executorService;
    }

    // 回收线程池资源
    public static void releaseExecutor(String executorName) {
        ExecutorService executorService = taskExecutors.remove(executorName);
        if (executorService != null) {
            executorService.shutdown();
        }
    }
}